package cn.tedu.coolshark.controller;

import cn.tedu.coolshark.entity.Product;
import cn.tedu.coolshark.mapper.ProductMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.io.File;
import java.util.Date;
import java.util.List;

@RestController
@RequestMapping("product")
public class ProductController {
    @Value("${dirPath}")
    private String dirPath;

    @Autowired
    ProductMapper mapper;

    @RequestMapping("insert")
    public void insert(@RequestBody Product product) {
        //设置商品的发布时间为当前的系统时间
        product.setCreated(new Date());
        mapper.insert(product);
    }

    @RequestMapping("select")
    public List<Product> select() {
        return mapper.select();
    }

    @RequestMapping("select/index")
    public List<Product> selectIndex() {
        return mapper.selectIndex();
    }

    @RequestMapping("delete")
    public void delete(int id) {
        //通过id查询到的商品的图片路径
        String url = mapper.selectUrlById(id);
        String filePath = dirPath+"/"+url;
        new File(filePath).delete();
        //删除数据中的数据
        mapper.deleteById(id);
    }

    @RequestMapping("select/top")
    public List<Product> selectTop() {
        List<Product> list = mapper.selectTop();
        for (Product p : list) {
            if (p.getTitle().length() > 3) {
                String title = p.getTitle().substring(0, 3) + "...";
                p.setTitle(title);
            }
        }
        return list;
    }

    @RequestMapping("select/category")
    public List<Product> selectByCid(int cid) {
        return mapper.selectByCid(cid);
    }

    @RequestMapping("search")
    public List<Product> selectByWd(String wd) {
        return mapper.selectByWd(wd);
    }

    @RequestMapping("selectById")
    public Product selectById(int id) {
        //当执行一次查询,就让浏览量+1
        mapper.updateViewCount(id);
        return mapper.selectById(id);
    }
}
